package com.carrental.vehicle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.exception.BusinessException;
import com.carrental.vehicle.entity.Store;
import com.carrental.vehicle.entity.Vehicle;
import com.carrental.vehicle.mapper.StoreMapper;
import com.carrental.vehicle.mapper.VehicleMapper;
import com.carrental.vehicle.service.StoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 门店服务实现类
 */
@Service
@RequiredArgsConstructor
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    private final VehicleMapper vehicleMapper;

    /**
     * 根据ID获取门店
     *
     * @param id 门店ID
     * @return 门店信息
     */
    @Override
    public Store getStoreById(Long id) {
        Store store = getById(id);
        if (store == null) {
            throw new BusinessException("门店不存在");
        }
        return store;
    }

    /**
     * 保存或更新门店
     *
     * @param store 门店信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateStore(Store store) {
        // 检查名称是否重复
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<Store>()
                .eq(Store::getName, store.getName())
                .eq(Store::getDeleted, 0);
        
        if (store.getId() != null) {
            queryWrapper.ne(Store::getId, store.getId());
        }
        
        long count = count(queryWrapper);
        if (count > 0) {
            throw new BusinessException("门店名称已存在");
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        if (store.getId() == null) {
            // 新增
            store.setCreateTime(now);
            store.setUpdateTime(now);
            store.setDeleted(0);
            return save(store);
        } else {
            // 更新
            store.setUpdateTime(now);
            return updateById(store);
        }
    }

    /**
     * 删除门店
     *
     * @param id 门店ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteStoreById(Long id) {
        // 检查门店是否存在
        Store store = getById(id);
        if (store == null) {
            throw new BusinessException("门店不存在");
        }
        
        // 检查是否有关联的车辆
        long count = vehicleMapper.selectCount(new LambdaQueryWrapper<Vehicle>()
                .eq(Vehicle::getStoreId, id)
                .eq(Vehicle::getDeleted, 0));
        
        if (count > 0) {
            throw new BusinessException("该门店下存在车辆，不能删除");
        }
        
        return removeById(id);
    }

    /**
     * 分页查询门店
     *
     * @param page  分页参数
     * @param store 查询条件
     * @return 分页结果
     */
    @Override
    public Page<Store> pageStore(Page<Store> page, Store store) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        
        queryWrapper.like(StringUtils.hasText(store.getName()), Store::getName, store.getName())
                .like(StringUtils.hasText(store.getProvince()), Store::getProvince, store.getProvince())
                .like(StringUtils.hasText(store.getCity()), Store::getCity, store.getCity())
                .like(StringUtils.hasText(store.getDistrict()), Store::getDistrict, store.getDistrict())
                .eq(Store::getDeleted, 0)
                .orderByDesc(Store::getCreateTime);
        
        return page(page, queryWrapper);
    }

    /**
     * 根据城市查询门店列表
     *
     * @param city 城市
     * @return 门店列表
     */
    @Override
    public List<Store> listStoreByCity(String city) {
        if (!StringUtils.hasText(city)) {
            throw new BusinessException("城市不能为空");
        }
        
        return list(new LambdaQueryWrapper<Store>()
                .eq(Store::getCity, city)
                .eq(Store::getDeleted, 0)
                .orderByDesc(Store::getCreateTime));
    }

    /**
     * 获取所有门店列表
     *
     * @return 门店列表
     */
    @Override
    public List<Store> listAllStores() {
        return list(new LambdaQueryWrapper<Store>()
                .eq(Store::getDeleted, 0)
                .orderByDesc(Store::getCreateTime));
    }
} 